﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agile.Engine.View;
using System.Collections;
using Agile.Engine;
using Agile.Engine.Data;
using System.Data;

namespace Fis.Win.Rules
{
    public class RateEditViewProvider : ClientViewProvider
    {

        public override bool ExecuteValidate(Hashtable viewModel)
        {

            if (View.ViewState == Agile.Engine.View.ViewState.AddNew)
            {
                DataAccess a = new DataAccess() { Context = DataContext, TableName = DataTableName };
                var d = viewModel["viewData"] as DataTable;


                if (0 < DataContext.DefaultModel.Count(DataTableName, "FCODE", string.Format("FCODE='{0}'", d.Rows[0]["FCODE"])))
                {
                    View.Message = "编码已存在。";
                    return false;
                }

                if (0 < DataContext.DefaultModel.Count(DataTableName, "FNAME", string.Format("FCODE='{0}'", d.Rows[0]["FNAME"])))
                {
                    View.Message = "名称已存在。";
                    return false;
                }
            }

            return true;
        }

        public override bool ExecuteUpdate(Hashtable viewModel)
        {
            ///验证失败
            if (!ExecuteValidate(viewModel))
            {
                return false;
            }

            var param = Fis.Win.Utils.AppSession.CreateServiceParamter(viewModel);
            param["viewData"] = Agile.Engine.Utils.ZipUtils.ZipDataTable(viewModel["viewData"] as DataTable);

            var exec = InvokeService(param);

            if (exec)
            {
                var data = Agile.Engine.Utils.ZipUtils.UnZipDataTable(ServiceProcess.Result["viewData"].ToString());
                DataAccess a = new DataAccess() { Context = DataContext, TableName = DataTableName };

                if (ViewState == Agile.Engine.View.ViewState.AddNew)
                {
                    a.AddNew(data.Rows[0]);
                }
                else
                {
                    a.Update(data.Rows[0]);
                }

                
            }
            return exec;
        }

        public override bool UpdateLocal(Hashtable args)
        {
            var d = args["viewData"] as DataTable;

            DataAccess a = new DataAccess() { Context = DataContext, TableName = DataTableName };

            var r = d.Rows[0];
            ///没有启用服务，需要生成ID
            if (IsEnableService)
            {
            }

            if (View.ViewState == Agile.Engine.View.ViewState.AddNew)
            {
                r["SID"] = Guid.NewGuid().ToString();
                a.AddNew(r);
            }
            else
            {
                a.Update(r);
            }
            return true;
        }

    }
}
